<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Activity;
use Illuminate\Http\Request;

class ActivityController extends Controller
{
    public function activityList($search = ""){
        if($search != ''){
            $allActivity = Activity::where('name', 'like', '%'.$search.'%')->paginate(6);
        }else{
            $allActivity = Activity::paginate(6);
        }
        return view('admin.activity',['items'=>$allActivity,'type'=>'list','searchWord'=>$search]);
    }
    public function activityHandler($type,$id = ''){
        if ($type == 'add'){
            if ($id != ''){
                return redirect('/admin/activity/edit/'.$id);
            }
            return view('admin.activity',['type'=>$type,'id'=>'new']);
        }else if($type == 'edit'){
            if ($id == ''){
                return redirect('/admin/activity/add');
            }
            $activity = Activity::findOrFail($id);
            return view('admin.activity',['type'=>$type,'id'=>$id,'name'=>$activity->name,'logo'=>$activity->logo,'cover'=>$activity->cover]);
        }else{
            abort('404');
        }
    }

    public function saveActivity(Request $request){
        $id = $request['id'];
        $logo = $request['logo'];
        $cover = $request['cover'];
        $name = $request['name'];
        if ($id == 'new'){
            $activity = new Activity();
        }else{
            $activity = Activity::findOrFail($id);
        }
        $activity->name = $name;
        $activity->logo = $logo;
        $activity->cover = $cover;
        $activity->save();
        return response()->json(['res'=>true,'msg'=>'保存成功']);
    }

    public function deleteActivity(Request $request){
        $id = $request['id'];
        Activity::find($id)->delete();
        return response()->json(['res'=>true,'msg'=>'删除成功']);
    }
}
